package net.pimpas.validation;

import java.util.ArrayList;
import java.util.List;

import net.pimpas.operation.exception.OperationException;
import net.pimpas.operation.operation.Operation;
import net.pimpas.operation.serviceprovider.OperationServiceProviderFactoryImpl;
import net.pimpas.validation.exception.ValidationException;
import net.pimpas.validation.result.ValidationResult;

public class DefaultValidation implements Validation {
	
	private List<Validation> childrens;
	private Validation parent;
	private Operation<?> operation;
	private String name;
	
	public DefaultValidation( String name, Operation<?> operation ) {
		this.setName(name);
		this.setOperation(operation);
		this.setChildrens(new ArrayList<Validation>());
	}

	public List<Validation> getChildrens() {
		return this.childrens;
	}

	public Validation getParent() {
		return this.parent;
	}

	@SuppressWarnings("unchecked")
	public void validate(ValidationResult result, Object... parameters) throws ValidationException {
		try {
			OperationServiceProviderFactoryImpl.getOperationServiceProvider()
				.call(this.getOperation(), result, parameters);
		} catch (OperationException e) {
			throw new ValidationException(e.getCause());
		}
	}

	public void setChildrens(List<Validation> childrens) {
		this.childrens = childrens;
	}

	public void setParent(Validation parent) {
		this.parent = parent;
	}

	public Operation<?> getOperation() {
		return operation;
	}

	public void setOperation(Operation<?> operation) {
		this.operation = operation;
	}

	public void addChild(Validation child) {
		if(child.getParent() != null)
			throw new IllegalStateException("Validation ["+child+"] already have parent!");
		this.getChildrens().add(child);
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}
	
	@Override
	public String toString() {
		return this.getName();
	}
}